package com.helloae.chap07;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;

import com.esri.arcgis.datasourcesfile.ShapefileWorkspaceFactory;
import com.esri.arcgis.geodatabase.IFeatureClass;
import com.esri.arcgis.geodatabase.IFeatureWorkspace;
import com.esri.arcgis.geodatabase.IGeoDataset;
import com.esri.arcgis.geodatabase.IGeoDatasetProxy;
import com.esri.arcgis.geodatabase.IGeoDatasetSchemaEdit;
import com.esri.arcgis.geodatabase.IGeoDatasetSchemaEditProxy;
import com.esri.arcgis.geometry.ISpatialReference;
import com.esri.arcgis.geometry.SpatialReferenceEnvironment;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;

/**
 * 将emidalat的坐标系赋给emidastrm<br>
 * 其实只是从emidalat的坐标文件prj.adf读取参考信息并赋给emidastrm<br>
 * 示例章节：7.4.2
 * @author zhushijie
 */
public class CopySpatialReference {

	public static void main(String[] args) throws UnknownHostException, IOException {
		// 初始化AE许可
		EngineInitializer.initializeEngine();
		AoInitialize ao = new AoInitialize();
		ao.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
		
		//使用ShapefileWorkspaceFactory.openFromFile的方法创建一个Workspace
		ShapefileWorkspaceFactory pWF = new ShapefileWorkspaceFactory();
		String ecliseWorkspace = System.getenv("Eclipse3.6Workspace");
		String path = ecliseWorkspace + "HelloAE" + File.separator
		+ "DataSet" + File.separator + "chap07";
		IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace) pWF
				.openFromFile(path, 0);
		//加载输入图层
		IFeatureClass pFeatureClass = pFeatureWorkspace
				.openFeatureClass("emidastrm");	
		
		IGeoDataset pTargetGD = new IGeoDatasetProxy(pFeatureClass);
		IGeoDatasetSchemaEdit pGeoDatasetEdit = new IGeoDatasetSchemaEditProxy(pFeatureClass);
		ISpatialReference pTargetSR = pTargetGD.getSpatialReference();
		
		//由于没有空间参考时才适合使用IGeoDatasetSchemaEdit.alterSpatialReference，因此这里需要判断：
		// 1. 没有空间参考；2. 文件的空间参考是可以更改的
		if("Unknown".equalsIgnoreCase(pTargetSR.getName()) && pGeoDatasetEdit.isCanAlterSpatialReference()){
			System.out.println("复制前的空间参考名为："+pTargetSR.getName());
			SpatialReferenceEnvironment pSpatRefFact = new SpatialReferenceEnvironment();
			ISpatialReference pProjCoordSys = pSpatRefFact.createESRISpatialReferenceFromPRJFile(path + File.separator + "emidalat"  + File.separator + "prj.adf");
			pGeoDatasetEdit.alterSpatialReference(pProjCoordSys);
			
			//输出现在的参考名，仅用于验证
			pTargetSR = pTargetGD.getSpatialReference();
			System.out.println("复制后的空间参考名为："+pTargetSR.getName());
		}
		
		ao.shutdown();
		System.out.println("Congratulations!");
	}

}
